﻿using Microsoft.Win32;
using PdfiumViewer;
using System.Drawing.Printing;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfPrintPDF;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        MakeRowInput("", 1);
    }

    //读取PDF文件夹
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        zujList.Children.Clear();
        //MakeRowInput("", 1);

        //读取目录中的pdf文件 
        OpenFolderDialog openFolderDialog = new OpenFolderDialog();
        if (openFolderDialog.ShowDialog() == true)
        {
            string dir = openFolderDialog.FolderName;

            //读取pdf文件
            var pdfList = System.IO.Directory.GetFiles(dir, "*.pdf");
            if (pdfList == null || pdfList?.Length == 0)
            {
                return;
            }
            process.Text = $"打印进度";

            int index = 1;
            foreach (var item in pdfList)
            {
                MakeRowInput(item, index);
                index++;
            }

        }
        ////读取pdf文件
        //for (int i = 0; i < 10; i++)
        //{
        //    MakeRowInput("", i);
        //}
    }

    public void MakeRowInput(string filePath, int index)
    {
        const int spanLabel = 40;
        DockPanel dockPanel = new DockPanel();
        dockPanel.Height = 22;
        dockPanel.Margin = new Thickness(0, 10, 0, 0);
        dockPanel.HorizontalAlignment = HorizontalAlignment.Left;

        int index2 = index;
        TextBlock textBlock = new TextBlock();
        textBlock.Text = $"序号{index2}.";
        textBlock.MinWidth = 40;
        //textBlock.Margin = new Thickness(20, 0, 0, 0);
        dockPanel.Children.Add(textBlock);

        dockPanel.Children.Add(new TextBlock() { Text = "pdf文件路径：", Margin = new Thickness(spanLabel, 0, 0, 0) });
        dockPanel.Children.Add(new TextBox() { Width = 400, Text = filePath, Name = "pdfPath" + index2 });


        TextBlock textBox = new TextBlock()
        {
            Text = "打印份数：",
            Margin = new Thickness(spanLabel, 0, 0, 0)
        };
        dockPanel.Children.Add(textBox);

        //份数输入框
        ToolTip myToolTip = new ToolTip();
        myToolTip.Content = new TextBlock() { Text = "份数为0不会打印" };
        var input = new TextBox()
        {
            Width = 80,
            Text = "50",
            Name = "fenshuNum" + index2,
            ToolTip = myToolTip,
        };
        input.MouseMove += (o, s) =>
        {
            myToolTip.IsOpen = true;
        };
        input.MouseLeave += (s, e) =>
        {
            myToolTip.IsOpen = false;
        };
        dockPanel.Children.Add(input);

        //方向输入框
        dockPanel.Children.Add(new TextBlock() { Text = "方向：", Margin = new Thickness(spanLabel, 0, 0, 0) });

        string guid = Guid.NewGuid().ToString("N");
        dockPanel.Children.Add(new RadioButton() { Content = "纵向", GroupName = "K1" + guid, IsChecked = true });
        dockPanel.Children.Add(new RadioButton() { Content = "横向", GroupName = "K1" + guid });

        string guid2 = Guid.NewGuid().ToString("N");
        dockPanel.Children.Add(new TextBlock() { Text = "纸张：", Margin = new Thickness(spanLabel, 0, 0, 0) });
        dockPanel.Children.Add(new RadioButton() { Content = "A3", GroupName = "P1" + guid2, IsChecked = true });
        dockPanel.Children.Add(new RadioButton() { Content = "A4", GroupName = "P1" + guid2 });

        zujList.Children.Add(dockPanel);
    }

    //批量设置份数
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        foreach (var item in zujList.Children)
        {
            var dockPanel = item as DockPanel;
            if (dockPanel == null)
            {
                continue;
            }
            foreach (var item2 in dockPanel.Children)
            {
                if (item2 is TextBox)
                {
                    var dom = item2 as TextBox;
                    if (dom != null && dom.Name.StartsWith("fenshuNum"))
                    {
                        dom.Text = this.txtNumTOP.Text;
                    }
                }
            }
        }
    }

    //批量设置方向，纵向
    private void fx_Click(object sender, RoutedEventArgs e)
    {
        SetRadioButton("纵向");
    }

    /// <summary>
    /// 批量设置打印方向
    /// </summary>
    /// <param name="typeName">纵向；横向</param>
    void SetRadioButton(string typeName)
    {
        foreach (var item in zujList.Children)
        {
            var dockPanel = item as DockPanel;
            if (dockPanel == null)
            {
                continue;
            }
            foreach (var item2 in dockPanel.Children)
            {
                if (item2 is RadioButton)
                {
                    var dom = item2 as RadioButton;
                    if (dom != null && dom.Content.Equals(typeName))
                    {
                        dom.IsChecked = true;
                    }
                }
            }
        }
    }

    //设置为横向
    private void hxClick(object sender, RoutedEventArgs e)
    {
        SetRadioButton("横向");
    }

    //设置为A3
    private void PaperSet(object sender, RoutedEventArgs e)
    {
        SetRadioButton("A3");
    }

    //设置为A4
    private void PaperSetA4(object sender, RoutedEventArgs e)
    {
        SetRadioButton("A4");
    }

    //批量设置份数
    private void txtNumTOP_KeyUp(object sender, KeyEventArgs e)
    {
        //回车事件
        if (e.Key == Key.Enter)
        {
            //MessageBox.Show("回车");
            Button_Click_1(null, e);
        }
    }

    int processDone = 0;
    //打印
    private void PrintClick(object sender, RoutedEventArgs e)
    {
        this.Dispatcher.Invoke(() =>
        {
            process.Text = $"打印进度0";
        });

        List<PrintSetInfo> list = new List<PrintSetInfo>();
        processDone = 0;
        foreach (var item in zujList.Children)
        {
            var dockPanel = item as DockPanel;
            if (dockPanel == null)
            {
                continue;
            }
            string pdfPath = string.Empty;//pdf路径
            short printNum = 0;//份数
            bool fangxiang = false;//方向；false为纵向；true为横向
            PaperKind paperType = PaperKind.A3;//纸张


            foreach (var item2 in dockPanel.Children)
            {

                //pdf路径
                if (item2 is TextBox)
                {
                    var dom = item2 as TextBox;
                    if (dom != null && dom.Name.StartsWith("pdfPath"))
                    {
                        pdfPath = dom.Text;
                        continue;
                    }
                }

                //份数
                if (item2 is TextBox)
                {
                    var dom = item2 as TextBox;
                    if (dom != null && dom.Name.StartsWith("fenshuNum"))//份数
                    {
                        if (!string.IsNullOrEmpty(dom.Text.Trim()))
                        {
                            short.TryParse(dom.Text, out printNum);
                            //printNum = Convert.ToInt32(dom.Text);
                            continue;
                        }
                    }
                }

                //方向
                if (item2 is RadioButton)
                {
                    var dom = item2 as RadioButton;
                    if (dom != null && dom.IsChecked == true && dom.Content.Equals("横向"))
                    {
                        fangxiang = true;
                        continue;
                    }
                }

                //纸张
                if (item2 is RadioButton)
                {
                    var dom = item2 as RadioButton;
                    if (dom != null && dom.IsChecked == true && dom.Content.Equals("A4"))
                    {
                        paperType = PaperKind.A4;
                        continue;
                    }
                }
            }

            list.Add(new PrintSetInfo()
            {
                PdfPath = pdfPath,
                PrintNum = printNum,
                Fangxiang = fangxiang,
                PaperType = paperType,
            });
        }

        if (list?.Count > 0)
        {
            //int total = list.Sum(g => g.PrintNum);
            int total = list.Count;
            foreach (var item in list)
            {
                Task.Run(() =>
                {
                    //打印
                    PrintPdf(item.PdfPath, item.PrintNum, item.PaperType, item.Fangxiang);
                    this.Dispatcher.Invoke(() =>
                    {
                        processDone++;
                        process.Text = $"打印进度{processDone}/{total}";
                    });
                });
            }
        }

    }


    /// <summary>
    /// 打印单个pdf
    /// </summary>
    /// <param name="pdf">文件路径</param>
    /// <param name="printNum">打印份数</param>
    /// <param name="paperKindSet">A3、A4</param>
    /// <param name="fx">false纵向，true横向</param>
    private void PrintPdf(string pdf, short printNum, PaperKind paperKindSet, bool fx = false)
    {
        if (printNum == 0)
        {
            return;
        }
        if (!File.Exists(pdf))
        {
            return;
        }

        // NewMethod1();
        // 加载PDF文档
        //var document = PdfiumViewer.PdfDocument.Load(pdf);

        var document = PdfiumViewer.PdfDocument.Load(pdf);

        // 创建打印文档对象
        var printDocument = document.CreatePrintDocument();

        // 设置打印机参数
        printDocument.PrinterSettings.Copies = printNum;//打印份数
        printDocument.PrinterSettings.FromPage = 0;
        //printDocument.PrinterSettings.ToPage = document.PageCount - 1;//不需要设置，会导致最后一页不会打印

        // 设置纸张方向为横向
        printDocument.DefaultPageSettings.Landscape = fx;

        // 配置A3纸张
        bool isA3Found = false;
        foreach (PaperSize paperSize in printDocument.PrinterSettings.PaperSizes)
        {
            if (paperSize.Kind == PaperKind.A3)
            {
                printDocument.DefaultPageSettings.PaperSize = paperSize;
                isA3Found = true;
                break;
            }
        }

        // 如果未找到A3，创建自定义A3尺寸（420mm x 297mm）
        if (!isA3Found)
        {
            int a3Width = (int)(420 / 25.4 * 100); // 420mm转换为百分之一英寸
            int a3Height = (int)(297 / 25.4 * 100);
            printDocument.DefaultPageSettings.PaperSize = new PaperSize("A3 Custom", a3Width, a3Height);
        }
        if (paperKindSet == PaperKind.A4)
        {
            foreach (PaperSize paperSize in printDocument.PrinterSettings.PaperSizes)
            {
                if (paperSize.Kind == PaperKind.A4)
                {
                    printDocument.DefaultPageSettings.PaperSize = paperSize;
                    break;
                }
            }
        }

        // 执行打印（需要处理打印权限和异常）
        printDocument.PrintController = new StandardPrintController(); // 静默打印
 

        //打印后显示文件名称
        //printDocument.DocumentName =DateTime.Now.Ticks.ToString()+".pdf";

        // 执行打印
        printDocument.Print();
    }
     
}